import { login, getUserInfo } from "../../api/sys.js"
import { setItem, getItem, removeAllItem } from "../../utils/storage.js";
import { TOKEN } from "../../constant/index.js";
import router from "../../router/index.js"
import { setTimeStamp} from "../../utils/auth";

export default {
    namespaced: true,
    state: () => ({
        token: getItem(TOKEN) || "",
        userInfo: {}
    }),
    mutations: {
        setToken(state, token) {
            state.token = token
            setItem(TOKEN, token)
        },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo
        }
    },
    actions: {
        /**
         *登录请求动作
         */
        login(context, userInfo) {
            const {username, password} = userInfo
            return new Promise((resolve, reject) => {
                login({
                    username,
                    password,
                })
                    .then(data => {
                        //console.log(data.data.data.AuthToken)
                        // this.commit("user/setToken", data.data.data.AuthToken)

                        //拦截后
                        console.log(data)
                        this.commit("user/setToken", data.AuthToken)
                        //跳转
                        router.push("/")
                        //保存登录时间
                        setTimeStamp()
                        resolve()
                    })
                    .catch(err => {
                        reject(err)
                    })
            })
        },
        /**
         *获取用户信息
         */
        async getUserInfo(context) {
           const res = await getUserInfo()
            console.log(res)
            this.commit("user/setUserInfo", res)
            return res
        },
        /**
         * 退出登录
         */
        logout() {
            this.commit("user/setToken", "")
            this.commit("user/setUserInfo", {})
            removeAllItem()
            //TODO 清理权限
            router.push("/login")
        }
    }
}



